<!-- 地址管理 -->
<template>
  <div class="addressManage sys-content">
    <page-mod>
      <el-card>
        <div class="query-box">
          <el-form :model="query" inline>
            <el-form-item label="所属地区:">
              <region-select v-model="region" ref="regionRefs"></region-select>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button icon="Search" color="#16b777" @click="load(1)">查询</el-button>
            <el-button icon="Plus" color="#FFB800" @click="show = true">新增</el-button>
            <el-button icon="Refresh" color="#FF5722" @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-card>
    </page-mod>
    <page-mod title="地址数据" icon="Guide" :showBtn="false" :padBottom="false">
      <el-card v-loading="loading" element-loading-text="拼命加载中" >
        <el-table ref="table" :data="dataList" max-height="493" row-key="id" border>
          <el-table-column label="序号" type="index" align="center" width="80"></el-table-column>
          <el-table-column label="收货地址" prop="fullName" header-align="center" width="300">
            <template #default="{row}">
              <span>{{ row.fullName.replace(/\//g,'') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="收货人姓名" prop="name" align="center"></el-table-column>
          <el-table-column label="收货人电话" prop="phone" align="center"></el-table-column>
          <el-table-column label="默认发货地址" prop="sendStatus" align="center">
            <template #default="{row}">
              <el-switch 
                v-model="row.sendStatus" 
                :active-value="1" 
                :inactive-value="0"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" 
                @change="sendChange(row)"/>
            </template>
          </el-table-column>
          <el-table-column label="默认收货地址" prop="receiveStatus" align="center">
            <template #default="{row}">
              <el-switch 
                v-model="row.receiveStatus" 
                :active-value="1" 
                :inactive-value="0" 
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                @change="receiveChange(row)"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180">
            <template #default="{row}">
              <el-button type="primary" icon="Edit" link @click="toUpdate(row.id)">修改</el-button>
              <el-divider direction="vertical" />
              <el-button type="danger" icon="Delete" link @click="doDelete(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          class="paging"
          v-show="query.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="query.current" 
          :page-size="query.size"
          :total="query.total"
          @current-change="load"
          @size-change="sizeChange">
        </el-pagination>
      </el-card>
    </page-mod>

    <!-- 新增、编辑弹窗 -->
    <el-dialog v-model="show" :title="form.id ? '编辑' : '新增'" top="10vh" width="40%" center draggable @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" size="default" label-width="120px">
        <el-form-item label="所属地区:" prop="region" required>
          <region-select v-model="form.region" ref="regionRef"></region-select>
        </el-form-item>
        <el-form-item label="详细地址:" prop="detailAddress" required>
          <el-input v-model="form.detailAddress" type="text" placeholder="请输入详细地址/例如：街道、小区、楼栋" clearable></el-input>
        </el-form-item>
        <el-form-item label="收货人:" prop="name" required>
          <el-input v-model="form.name" type="text" placeholder="请输入收货人姓名" clearable class="input-w"></el-input>
        </el-form-item>
        <el-form-item label="手机号:" prop="phone" required>
          <el-input v-model="form.phone" type="text" placeholder="请输入手机号" clearable class="input-w"></el-input>
        </el-form-item>
        <el-form-item v-if="!form.id" label="默认发货地址:" prop="sendStatus">
          <el-radio-group v-model="form.sendStatus">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="!form.id" label="默认收货地址:" prop="receiveStatus">
          <el-radio-group v-model="form.receiveStatus">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="doSubmit">保存</el-button>
        <el-button size="default" @click="show = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="addressManage">
  import { cudAddressApi, getAddressListPagesApi, getAddressInfoApi, updateReceiveAddresStatusApi, updateSendAddresStatusApi } from '@/api/api'
  import { regexPhone } from '@/utils/utils'
  import { ref, reactive, toRefs, getCurrentInstance, onActivated } from 'vue'

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties
  
  const formRef = ref(null)
  const regionRefs = ref(null)
  const regionRef = ref(null)

  const currentData = reactive({
    loading: false,
    selectLoading: false,
    show: false,
    query: {
      provinceCode: '',
      cityCode: '',
      regionCode: '',
      current: 1,
      size: 20,
      total: 0
    },
    region: [],
    dataList: [],
    form: {
      id: '',
      provinceCode: '',
      cityCode: '',
      regionCode: '',
      detailAddress: '',
      name: '',
      phone: '',
      sendStatus: 1,
      receiveStatus: 1,
      region: []
    },
    rules: {
      detailAddress: [{ required: true, message: '请输入详细地址', trigger: ['blur', 'change'] }],
      name: [{ required: true, message: '请输入收货人姓名', trigger: ['blur', 'change'] }],
      phone: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value) {
              callback(new Error('请输入手机号'))
            } else {
              if(!regexPhone(value)) {
                callback(new Error('手机号必须是11位，请重新输入'))
              } else {
                callback()
              }
            }
          } 
        }
      ],
      region: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value.length) {
              callback(new Error('请选择省、市、区县'))
            } else if(value.length === 1) {
              callback(new Error('请选择市、区县'))
            } else if(value.length === 2) {
              callback(new Error('请选择区县'))
            } else if(value.length === 3) {
              callback()
            }
          } 
        }
      ]
    }
  })
  let {loading, selectLoading, show, query, region, dataList, form, rules} = toRefs(currentData)

  // 查询
  function load(page) {
    currentData.loading = true
    currentData.query.current = page
    currentData.query.provinceCode = currentData.region[0] || ''
    currentData.query.cityCode = currentData.region[1] || ''
    currentData.query.regionCode = currentData.region[2] || ''
    getAddressListPagesApi(currentData.query).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data.pages
        currentData.query.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 新增或编辑
  function doSubmit() {
    formRef.value.validate((valid) => {
      if (valid) {
        currentThis.$messageBox.confirm(`确认${currentData.form.id ? '修改' : '新增'}吗？`).then(() => {
          let loading = currentThis.$loading(`正在${currentData.form.id ? '修改' : '新增'}`)
          currentData.form.provinceCode = currentData.form.region[0]
          currentData.form.cityCode = currentData.form.region[1]
          currentData.form.regionCode = currentData.form.region[2]
          cudAddressApi(`${currentData.form.id ? 'update' : 'save'}`, currentData.form).then(res => {
            loading.close()
            if(res.code === '200') {
              currentThis.$message.success(res.message)
              currentData.show = false
              load(currentData.form.id ? currentData.query.current : 1)
            } else {
              currentThis.$message.error(res.message)
            }
          })
        }).catch(() => {})
      } else {
        return false;
      }
    })
  }

  // 修改弹窗
  function toUpdate(id) {
    getAddressInfoApi(id).then(res => {
      if(res.code === '200') {
        currentData.form = res.data
        currentData.form.region = [res.data.provinceCode, res.data.cityCode, res.data.regionCode]
        currentData.show = true
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 删除
  function doDelete(id) {
    currentThis.$messageBox.confirm('确认删除吗？').then(() => {
      let loading = currentThis.$loading('删除中，请耐心等待')
      cudAddressApi('delete', { id: id }).then(res => {
        loading.close()
        if(res.code === '200') {
          currentThis.$message.success(res.message)
          load(currentData.query.current)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 修改默认发货地址
  function sendChange(e) {
    updateSendAddresStatusApi(e.id, e.sendStatus).then(res => {
      if(res.code === '200') {
        load(currentData.query.current)
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 修改默认收货地址
  function receiveChange(e) {
    updateReceiveAddresStatusApi(e.id, e.receiveStatus).then(res => {
      if(res.code === '200') {
        load(currentData.query.current)
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 重置表单
  function resetForm() {
    currentData.form = {
      id: '',
      provinceCode: '',
      cityCode: '',
      regionCode: '',
      detailAddress: '',
      name: '',
      phone: '',
      sendStatus: 1,
      receiveStatus: 1,
      region: []
    }
    formRef.value.resetFields()
    regionRef.value.resetData()
  }

  // 重置查询
  function resetSearch() {
    currentData.query.provinceCode = ''
    currentData.query.cityCode = ''
    currentData.query.regionCode = ''
    currentData.region = []
    regionRefs.value.resetData()
    load(1)
  }

  function sizeChange(size) {
    currentData.query.size = size
    this.load(1)
  }

  onActivated(() => {
    load(currentData.query.current)
  })
</script>

<style lang="less" scoped>
.addressManage{
  :deep(.el-dialog){
    .input-w{
      width: 190px;
    }
  }
}
</style>